/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.groupb.circus.Databases;

import com.groupb.circus.interfaces.DBAction;
import com.groupb.circus.interfaces.DBActionResult;
import com.groupb.circus.interfaces.DBManager;
import com.groupb.circus.interfaces.XmlDbDataSource;
import java.io.IOException;
import java.lang.reflect.Method;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.xmldb.api.base.ResourceSet;
import org.xmldb.api.base.XMLDBException;
import org.exist.xmldb.XQueryService;
import org.xmldb.api.base.Collection;
import org.xmldb.api.base.ResourceIterator;
import org.xmldb.api.modules.XMLResource;
import org.xmldb.api.modules.XUpdateQueryService;

/**
 *
 * @author a
 */
public class DBManagerIm implements DBManager {

    XmlDbDataSource xmlds = null;
    static private DBManager dbm;
    static Properties pp;
    List Photo;
    private static final Log LOG = LogFactory.getLog(DBManager.class);

    /**
     * Singleton Pattern
     *
     * @throws XMLDBException
     * @throws InstantiationException
     * @throws IllegalAccessException
     */
    private DBManagerIm() throws XMLDBException, InstantiationException, IllegalAccessException {
        
        xmlds = XmlDbDataSourceIm.getInstance();
    }
    
    /**
     * 
     * @return dbm
     * @throws XMLDBException
     * @throws InstantiationException
     * @throws IllegalAccessException 
     */
    public static DBManager getInstance() throws XMLDBException, InstantiationException, IllegalAccessException {

        if (dbm == null) {
            dbm = new DBManagerIm();
            pp = new Properties();
            try {
                
                pp.load(DBManagerIm.class.getClassLoader().getResourceAsStream("conquery.properties"));

            } catch (IOException ex) {
                
                Logger.getLogger(DBManagerIm.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        return dbm;
    }

    /**
     * 
     * @param aDBAction
     * @return DBActionResult
     */
    @Override
    public DBActionResult execute(DBAction aDBAction) {
        
        
        DBActionResult dbAr = new DBActionResultIm();

        String actionId = aDBAction.getActionId();
        String[] parameters = (String[]) aDBAction.getParameters();

        String querytype = "";
        Collection col;
        List<Images> prueba = new ArrayList();
        List<News> prueba_dos = new ArrayList();
        try {

            //Check if the query type is an update or a specific query 
            querytype = aDBAction.getActionId().substring(0, aDBAction.getActionId().indexOf("."));

            dbm = new DBManagerIm();

            //replace parameters in the query
            MessageFormat form = new MessageFormat(pp.getProperty(actionId));
            String q = form.format(parameters);

            XQueryService service;
            XUpdateQueryService updateservice;

            //execute the query
            
            col = (Collection) XmlDbDataSourceIm.getInstance().getCollection();
            if (LOG.isDebugEnabled()) {
                
                LOG.debug(col);
            }


            if (querytype.equalsIgnoreCase("query")) {
                
                service = (XQueryService) col.getService("XQueryService", "1.0");
                ResourceSet result = service.query(q);
                
                
                
                
                
               // PhotoHandler 
             ResourceIterator i = result.getIterator();
                
             while(i.hasMoreResources()) {
                 
                XMLResource r = (XMLResource) i.nextResource();
		Images Ima = new Images();
                PhotoHandler handler = new PhotoHandler(Ima);
		r.getContentAsSAX(handler);
                prueba.add(Ima);
		
        }
               
               dbAr.setResult(prueba);
               
            }
            
            if (querytype.equalsIgnoreCase("news")) {
                
                
                service = (XQueryService) col.getService("XQueryService", "1.0");
                ResourceSet result_dos = service.query(q);
                
               
               // NewsHandler 
             ResourceIterator i = result_dos.getIterator();
                
             while(i.hasMoreResources()) {
                 
                XMLResource r = (XMLResource) i.nextResource();
		News notice = new News();
                NewsHandler newshandler = new NewsHandler(notice);
		r.getContentAsSAX(newshandler);
                prueba_dos.add(notice);
		
        }
               
               dbAr.setResult(prueba_dos);
                
                
            }

            if (querytype.equalsIgnoreCase("update")) {

                updateservice = (XUpdateQueryService) col.getService("XUpdateQueryService", "1.0");
                updateservice.update(q);
            }

        } catch (XMLDBException ex) {
            Logger.getLogger(DBManager.class.getName()).log(Level.SEVERE, null, ex);

            dbAr.setErrorMsg(ex.getMessage());
            dbAr.setException(ex);

        } finally {
            try {
                DBManagerIm.class.getClassLoader().getResourceAsStream("conquery.properties").close();
            } catch (IOException ex) {
                Logger.getLogger(DBManager.class.getName()).log(Level.SEVERE, null, ex);
            } finally {
                return dbAr;
            }
        }
    }
}